﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Box.Cliente.Control
{
    public partial class frmAdministrarRoles : System.Web.UI.Page
    {
        public bool puedeCrear;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {

                object user = Request.QueryString["user"];

                object userelim = Request.QueryString["userelim"];

                if (user != null)
                {
                    lblUsuario.Text = user.ToString();

                    string[] rolesForUser = Roles.GetRolesForUser(lblUsuario.Text);

                    lbRolesForUser.DataSource = rolesForUser;
                    lbRolesForUser.DataBind();

                    string[] allRoles = Roles.GetAllRoles();

                    IEnumerable<string> rolesDisp = allRoles.Except(rolesForUser);

                    lbRoles.DataSource = rolesDisp;
                    lbRoles.DataBind();

                    if (lbRoles.Items.Count == 0)
                    {
                        btnAgregar.Enabled = false;
                    }

                    if (lbRolesForUser.Items.Count == 0)
                    {
                        btnQuitar.Enabled = false;
                    }
                    
                }
                else if (userelim != null)
                {
                    Membership.DeleteUser(Request.QueryString["userelim"], true);

                    Response.Redirect("frmListUsuarios.aspx");
                }
            }

            this.DataBind();
        }

        protected void btnCrearRol_Click(object sender, EventArgs e)
        {
            
        }

        protected void btnAgregar_Click(object sender, EventArgs e)
        {
            if (lbRoles.SelectedItem != null)
            {
                Roles.AddUserToRole(lblUsuario.Text, lbRoles.SelectedItem.Text);
                Response.Redirect("frmAdministrarRoles.aspx?user=" + lblUsuario.Text);
            }
        }

        protected void btnQuitar_Click(object sender, EventArgs e)
        {
            if (lbRolesForUser.SelectedItem != null)
            {
                Roles.RemoveUserFromRole(lblUsuario.Text, lbRolesForUser.SelectedItem.Text);
                Response.Redirect("frmAdministrarRoles.aspx?user=" + lblUsuario.Text);
            }
        }

        protected void btnCancelar_Click(object sender, EventArgs e)
        {
            Response.Redirect("frmListUsuarios.aspx");
        }
    }
}